import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

// 打印请求信息
@WebServlet("/showRequest")
public class ShowRequestServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 把 api 的执行结果，往这个 StringBuilder 里面塞
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("<h3>首行部分</h3>");
        stringBuilder.append(req.getProtocol());//返回协议的版本号
        stringBuilder.append("<br>");
        stringBuilder.append(req.getMethod());//返回请求的HTTP方法的名称
        stringBuilder.append("<br>");
        stringBuilder.append(req.getRequestURI());//返回请求的URL的一部分
        stringBuilder.append("<br>");
        stringBuilder.append(req.getContextPath());//返回请求上下文的请求URL部分
        stringBuilder.append("<br>");
        stringBuilder.append(req.getQueryString());//返回URL中的查询字符串
        stringBuilder.append("<br>");
        stringBuilder.append("<h3>header 部分 <h3>");
        Enumeration<String> headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()){
            String heardName = headerNames.nextElement();
            String heardValue = req.getHeader(heardName);
            stringBuilder.append(heardName +" : " + heardValue + "<br>");
        }
        resp.setContentType("text/html;charset=utf8");
        resp.getWriter().write(stringBuilder.toString());
    }
}
